package com.rabbit.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rabbit.db.entity.File;
import com.rabbit.mapper.FileMapper;
import com.rabbit.service.FileService;
import com.rabbit.service.OssService;
import com.rabbit.vo.req.FileReq;
import com.rabbit.vo.res.FileRes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * <h1>文件中心业务实现</h1>
 *
 * @author zjw
 * @date 2022/2/15 21:58
 */
@Service
public class FileServiceImpl implements FileService {

    @Resource
    private FileMapper fileMapper;

    @Resource
    private OssService ossService;

    @Value("${upload.tmp.dir}")
    private String uploadTmpDir;

    @Override
    public PageInfo<FileRes> queryFiles(FileReq fileReq) {
        File file = File.builder().build();
        BeanUtils.copyProperties(fileReq, file);
        return PageHelper.startPage(fileReq.getPage(), fileReq.getLimit())
                .doSelectPageInfo(() -> fileMapper.queryFiles(file));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFile(FileReq fileReq) {
        File file = fileMapper.selectByPrimaryKey(fileReq.getFileId());
        ossService.deleteObject(file.getFileUrl());
        fileMapper.deleteByPrimaryKey(fileReq.getFileId());
    }

    @Override
    public void downloadFile(Long fileId, HttpServletResponse response) {
        File file = fileMapper.selectByPrimaryKey(fileId);
        ossService.downloadFile(file.getFileUrl(), response);
    }
}
